package com.flex.service.impl;

import com.flex.dto.AccountDTO;
import com.flex.entity.Account;
import com.flex.exception.BusinessException;
import com.flex.mapper.AccountMapper;
import com.flex.service.AccountService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.DateUtil;
import com.mybatisflex.core.util.UpdateEntity;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.flex.entity.table.AccountTableDef.ACCOUNT;


@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Autowired
    AccountMapper mapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertAccount(AccountDTO accountDto) {
        Account account = new Account();
        BeanUtils.copyProperties(accountDto, account);
        account.setBirthday(DateUtil.parseDate(accountDto.getBirthday()));
        int b = mapper.insert(account);
        if (b >= 1) {
            return true;
        }
        return false;
    }

    @Override
    public List<Account> getAllAccountList() {
        List<Account> list = mapper.selectAll();
        return list;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean updateAccountById(String id, String name) {
        Account account = UpdateEntity.of(Account.class,id);
        //与上一行作用相同
        // Account account = mapper.selectOneById(id);
        account.setUserName(name);
        int b = mapper.update(account);
        if (b >= 1) {
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteAccountById(String id) {
        // 方法一：
        // int b = mapper.deleteByCondition(ACCOUNT.ID.eq(id));

        //方法2：
        // int b = mapper.deleteById(id);

        //方法3：
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(ACCOUNT.ACCOUNT_ID.eq(id));
        int b = mapper.deleteByQuery(queryWrapper);
        if (b >= 1) {
            return true;
        }
        return false;
    }
}
